<template>
  <div>
    <div class="pop-up" v-if="associationRules">
      <i class="el-icon-error" @click="handleclose"></i>
      <div class="pop-content">
        <div class="title_name">{{ add_from.id ? "编辑" : "新增" }}</div>
        <el-form label-width="120px">
          <el-form-item label="分类" :required="true">
            <el-select
              v-model="add_from.questionTypeName"
              placeholder="请选择"
              class="pop-input"
            >
              <el-option
                v-for="item in typeList"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标题" :required="true">
            <el-input v-model="add_from.title" class="pop-input"></el-input>
          </el-form-item>
          <!-- <el-form-item label="图片/视频" :required="true" v-if="is_imageText">
            <el-radio-group v-model="add_from.fileType">
              <el-radio :label="0">图片</el-radio>
              <el-radio :label="1">视频</el-radio>
            </el-radio-group>
            <div v-if="add_from.fileType == 0">
              <el-upload
                :action="uploaddata.url"
                :data="uploaddata.data"
                :headers="uploaddata.headers"
                class="upload-demo"
                accept=".png,.jpg,.jpeg"
                :on-preview="handlePreview"
                :http-request="uploadFile"
                multiple
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileMonitoring"
                :on-change="onchangeMonitoring"
                :before-remove="beforeremoveMonitoring"
                ref="uploadc"
              >
                <el-button
                  type="primary"
                  class="icon-search exportbtn"
                  style="width: 100px"
                  @click="handleUpload"
                  >上传</el-button
                >
              </el-upload>
            </div>
            <div v-else>
              <el-upload
                :action="uploaddata.url"
                :data="uploaddata.data"
                :headers="uploaddata.headers"
                class="upload-demo"
                accept=".mp4"
                :on-preview="handlePreview"
                :http-request="uploadFile"
                multiple
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileMonitoring"
                :on-change="onchangeMonitoring"
                :before-remove="beforeremoveMonitoring"
                ref="uploadc"
              >
                <el-button
                  type="primary"
                  class="icon-search exportbtn"
                  @click="handleUpload"
                  >上传</el-button
                >
              </el-upload>
            </div>
          </el-form-item> -->
          <!-- <el-form-item label="发布者" :required="true">
            <el-input v-model="add_from.publisher" class="pop-input"></el-input>
          </el-form-item>
          <el-form-item label="发布时间" :required="true">
            <el-date-picker
              v-model="add_from.publishTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:ss:mm"
              class="pop-input"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item> -->
          <el-form-item label="排序" :required="true">
            <el-input v-model="add_from.sort" class="pop-input"></el-input>
          </el-form-item>
          <el-form-item label="状态" :required="true">
            <el-radio-group v-model="add_from.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <!--   <el-form-item label="状态" :required="true">
            <el-radio-group v-model="add_from.state">
              <el-radio :label="0">下架</el-radio>
              <el-radio :label="1">发布</el-radio>
              <el-radio :label="2">定时发布</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="定时发布时间"
            :required="true"
            v-if="add_from.state == 2"
          >
            <el-date-picker
              v-model="add_from.scheduleTime"
              type="time"
              value-format="YYYY-MM-DD HH:ss:mm"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="来源" :required="true">
            <el-radio-group v-model="add_from.source">
              <el-radio :label="0">原创</el-radio>
              <el-radio :label="1">转载</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="内容" :required="true">
            <el-radio-group v-model="add_from.contentType">
              <el-radio :label="0">图文</el-radio>
              <el-radio :label="1">连接</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" v-if="add_from.contentType == 1">
            <el-radio-group
              v-model="add_from.linkType"
              v-if="add_from.contentType == 1"
            >
              <el-radio :label="0">内链</el-radio>
              <el-radio :label="1">外链</el-radio>
            </el-radio-group>
          </el-form-item> -->
          <el-form-item
            label=""
            :required="true"
            v-show="add_from.contentType == 0 || add_from.contentType == null"
            ><div class="mgb20" ref="editor"></div>
          </el-form-item>
          <el-form-item label="链接" v-if="add_from.contentType == 1">
            <el-input class="width_accout" v-model="add_from.link"></el-input>
          </el-form-item>
        </el-form>
        <div>
          <el-button @click="handleclose" class="icon-search1">取消</el-button>
          <el-button type="primary" class="icon-search" @click="handleSaveEdit"
            >确定</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import WangEditor from "wangEditor";
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { dictionaries } from "../assets/js/dictionaries";
import api from "../api/api";
import axios from "axios";
export default {
  components: {},
  setup(props, context) {
    console.log(context.attrs);
    const associationRules = ref(context.attrs.associationRules);
    const add_from = reactive(context.attrs.add_from);
    const typeList = reactive(context.attrs.typeList);
    const is_imageText = context.attrs.is_imageText;
    const handleclose = () => {
      associationRules.value = false;
      context.emit("handleclose", associationRules.value);
    };
    const newdateTime = ref("");
    const editor = ref(null);
    const content = reactive({
      html: "",
      text: "",
    });
    const parameterType = ref([]);
    dictionaries("problemTypes").then((res) => {
      parameterType.value = res;
    });
    const fileMonitoring = ref([]);
    let instance;
    onMounted(() => {
      instance = new WangEditor(editor.value);
      instance.config.zIndex = 1;
      var token = localStorage.getItem("token");
      instance.config.customUploadImg = (files, insert) => {
        var formData = new FormData();
        for (var i = 0; i < files.length; i++) {
          formData.append("file", files[i], files[i].name); //  多张图片文件都放进一个form-data，有些小伙伴说这里应该这样写：formData.append("file[" + i + "]", files[i], files[i].name)，后端才能拿到完整的图片数组，其实不然，用这个formData.getAll("file")方法恰好拿到数组，或者也可以forEach获取，有很多种办法。
        }
        axios({
          method: "post",
          url: api.getUrl() + "auth/account/uploadFile",
          data: formData,
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: "Bearer " + token,
          },
        })
          .then((da) => {
            if (da.data.code == 1) {
              insert(da.data.data);
            } else {
              ElMessage.error("上传失败");
            }
          })
          .catch((err) => {});
        // axios
        //   .post(api.getUrl() + "sys/file/uploadPublic", formData, {
        //     // 上传图片接口
        //     headers: {
        //       "Content-Type": "application/json",
        //       token: localStorage.getItem("token"),
        //       Authorization: "Bearer " + localStorage.getItem("token"),
        //     },
        //   })
        //   .then((da) => {
        //     console.log(da);
        //     if (da.data.code == 1) {
        //       insert(da.data.data.tempUrl);
        //     } else {
        //       alert(da.data.data.message);
        //       return;
        //     }
        //   });
      };
      instance.create();
      setTimeout(function () {
        instance.txt.html(add_from.content);
        if (add_from.fileUrl) {
          fileMonitoring.value[0] = {
            name: add_from.fileName,
            url: add_from.fileUrl,
          };
        }
      }, 100);
    });
    onBeforeUnmount(() => {
      instance.destroy();
      instance = null;
    });
    const handleSaveEdit = () => {
      add_from.content = instance.txt.html();
      context.emit("handleSaveEdit", add_from);
    };
    const uploaddata = ref({});
    const handleUpload = () => {
      uploaddata.value = {
        url: api.getUrl() + "auth/account/uploadFile",
        data: {},
        headers: {
          "Content-Type": "application/json", //配置请求头
          Authorization: "Bearer " + localStorage.getItem("token"),
        },
      };
    };
    const onchangeMonitoring = (file, fileList) => {
      add_from.fileName = "";
      add_from.fileUrl = "";
      if (file.response && file.response.code == 1) {
        add_from.fileName = file.response.data.fileName;
        add_from.fileUrl = file.response.data.url;
      }
    };
    const beforeremoveMonitoring = (file, fileList) => {
      add_from.fileName = null;
      add_from.fileUrl = null;
    };
    return {
      is_imageText,
      typeList,
      uploaddata,
      associationRules,
      add_from,
      editor,
      content,
      newdateTime,
      parameterType,
      handleclose,
      handleSaveEdit,
      handleUpload,
      onchangeMonitoring,
      beforeremoveMonitoring,
      fileMonitoring,
    };
  },
};
</script>
<style lang="less" scoped>
@import "../assets/css/common.css";
.pop-up {
  z-index: 999;
}
.el-icon-error {
  color: #fff;
  position: fixed;
  right: 50px;
  top: 40px;
  font-size: 30px;
}
.icon-search {
  position: absolute;
  right: 30px;
  width: 150px;
}
.icon-search1 {
  position: absolute;
  right: 220px;
  width: 150px;
}
&:deep(.el-upload--text) {
  background-color: none;
  border: 0px dashed #d9d9d9;
  height: 40px;
  width: 150px;
}
.pop-input {
  width: 450px;
}
</style>
